
--  NewTeamReadyAndSettingController

local NewTeamReadyAndSettingView = import("..views.NewTeamReadyAndSettingView")
local PvpMatchView = require("app.pvp.views.PvpMatchView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(params)
	self.super.ctor(self, params)
end

function ClassRef:init()
	self._model = app:getInst("TeamModel")
end

function ClassRef:listEvent()
	return {
		"onTeamUpdate",
		"onTeamMemberUpdate",
	}
end


function ClassRef:onEvent(eventName, data)
	if eventName == "onTeamUpdate" then
		self:refreshMember()
		self:refreshTeamMemberReadyStatus()
		self:refreshTeamCombatPower()
	elseif eventName == "onTeamMemberUpdate" then -- 成员变化
		-- onTeamMemberUpdate 消息收到时肯定能收到onTeamUpdate
		-- self:refreshMember()
		-- self:refreshTeamMemberReadyStatus()
		-- self:refreshTeamCombatPower()

		-- if self._model:isMyTeam() then
		-- 	self:refresReadyUIBtnFunctionName( L("lua_code_text_137") )
		-- else
		-- 	self:refresReadyUIBtnFunctionName( L("lua_code_text_258") )
		-- end
	end
end

-- data = {
-- 	idx = 1/2, -- 1(准备界面) 2(别人的队伍设置),
-- 	targetId = number, -- 目标id
-- 	team = TeamVo, -- 队伍信息，idx=2生效
-- 	isMatch = true/false, -- 是否是匹配
-- }
function ClassRef:openView(data)
	self._idx = data.idx
	self._targetId = data.targetId
	self._teamTarget = self._model:getTeamTargetById(self._targetId)
	self._otherTeam = data.team
	self._isMatch = data.isMatch or false

	-- 检查全员是否准备好，准备好的直接开始，否则发起投票
	local idx = data.idx
	local team = self._model:getTeam()
	if idx == 1 and team:isMyTeam() then
		if team:isAllWithTeam() then
			if self._teamTarget:isPveType() then
				if self._isMatch then
					self:_startCrossDungeonMatch()
				else
					self:_enterDungeons()
				end
			else
				-- pvp都是走match
				self:_startPVPMatch()
			end
			return
		else
			self._model:reqStartVote(self._targetId, self._isMatch)
		end
	end

	if cc.isDead(self._view) then
		self._view = NewTeamReadyAndSettingView.new( app.mvc.VIEWTYPE_BLUR, data )
		self._view:onCloseView(handler(self, self.closeView))
		self._view:onClearView(handler(self, self.clearView))
		self._view:onOperate(handler(self, self._onOperate))

		local openBtn = app:sendMsg("IMRoomController", "getIMOpenBtn")
		if openBtn then
			self._view:addChild(openBtn, 2)
		end
	end
	self:addChild(self._view, {notDelete=(idx==1)})

	self._view:showWhichPanelByIdx(idx)
	self._view:show()
	self:refreshTeamTargetStr()

	local btnName = L("lua_code_text_258")
	if self._model:isMyTeam() then
		btnName = self._isMatch and L("lua_code_text_164") or L("lua_code_text_137")
	end
	self:refresReadyUIBtnFunctionName( btnName )

	if 1 == idx then --战备UI才需要显示战斗力
		AM.playSoundById(6233)
		self._model:reqGetTeamInfo()

		self:refreshMember()
		self:refreshTeamMemberReadyStatus()
		self:refreshTeamCombatPower()

		self._view:setTipsShown( true )
	elseif 2 == idx then -- 设置UI
		self:refreshTeamSetting( self._otherTeam )
		self._view:setTipsShown()
	end
end
function ClassRef:closeView(data)
	if self._view then
		self._view:removeCreateTeamDialog()
		self:removeChild(self._view, data)
		self:clearView()
	end
end
function ClassRef:clearView(data)
	if self._view then self._view = nil end

	-- clear data cache
	self._idx = nil
	self._targetId = nil
	self._teamTarget = nil
	self._otherTeam = nil

	if cc.isAlive(self._kickDlg) then
		self._kickDlg:removeFromParent()
		self._kickDlg = nil
	end
end

function ClassRef:openDungeonMatchView(targetId, curSeconds)
	-- 开始匹配，必定关闭准备界面
	self:closeView()

	-- 模拟点击停止，其他的方法没找到
	app:getLaunchCtl():endCharacterMove()

	local viewName = PvpMatchView:getViewName()
	local view = UIHandler:getPopupUiByKey(viewName)
	if not view then
		view = PvpMatchView.new()
		view:onCloseView(function(sender)
			UIHandler:removePopupUiByKey(sender:getViewName())
		end)
		view:onOperate(function(op, params)
				if op == "cancel" then
					self._model:C2S_CancelTeamTargetMatch()
				end
			end)
		UIHandler:addPopupUi(view, view:getViewName())
	end
	view:refresh(60, curSeconds, self._model:pvpMatchingEnabled())
	view:setTipContent(L("team_text1"))
	view:show()
end

function ClassRef:closeDungeknMatchView()
	local view = UIHandler:getPopupUiByKey(PvpMatchView:getViewName())
	if view then
		view:closeView()
	end
end

-- 单人开始副本
-- 组队查找器进入副本的逻辑都在这里，单人开始的逻辑也放这里
function ClassRef:singleStart(teamTarget)
	if teamTarget:isPveType() then --PVE
		self:_enterDungeons(teamTarget)
	else -- PVP
		self:_startPVPMatch(teamTarget)
	end
end

-- 单人匹配副本
function ClassRef:singleMatch(teamTarget)
	if teamTarget:isPveType() then
		self:_startCrossDungeonMatch(teamTarget)
	else
		self:_startPVPMatch(teamTarget)
	end
end

-- 暂未使用
-- 队伍准备好之后开始副本(只处理pve，pvp各自处理自己的开始)
function ClassRef:teamReadyStart(teamTarget)
	if teamTarget:isPveType() then --PVE
		self:_enterDungeons(teamTarget)
	end
end

------------------------------ view logic ---------------------------------
-- 队员收到投票通知
function ClassRef:teamMemberStartVote( targetId, isMatch )
	if not self:isViewVisible() then
		self:openView( { idx=1, targetId=targetId, isMatch=isMatch } )
	else
		self:refreshTeamMemberReadyStatus()
	end
	self:refresReadyUIBtnFunctionName( L("lua_code_text_258") )
end

function ClassRef:refreshTeamCombatPower()
	if not self:isViewAlive() then return end

	local combat = self._model:getTeamTotalCapacity(true)
	self._view:refreshTeamCombatPower( combat )
end

function ClassRef:refreshMember()
	if not self:isViewAlive() then return end
	local maxNum = self._teamTarget:getMaxNum()
	local team = self._model:getTeam()
	self._view:refreshTeamMember(maxNum, team)

	-- 显示随从
	if self._teamTarget:isWithPartner() then
		self._view:refreshPartnerInfo(maxNum, team:getLeaderPartnerInfo())
	end
end

-- 刷新装备UI按钮功能名字
function ClassRef:refresReadyUIBtnFunctionName( btnName )
	if not self:isViewAlive() then return end
	self._view:refresReadyUIBtnFunctionName( btnName )
end

-- 刷新队伍成员准备状态
function ClassRef:refreshTeamMemberReadyStatus()
	if not self:isViewAlive() then return end

	local team = self._model:getTeam()
	local isLegion = team:isLegion()
	local memberNum = team:getMemberNum()
	local robotNum = team:getRobotNum()
	self._view:refreshTeamMemberReadyStatus(isLegion, memberNum, robotNum)
end

-- 刷新队伍设置
function ClassRef:refreshTeamSetting( newTeamVo )
	if not self:isViewAlive() then return end

	if newTeamVo then
		self._view:refreshTeamSetting( newTeamVo )
	else
		self._view:refreshTeamSetting( self._model:getTeam() )
	end
end

-- 刷新队伍目标
function ClassRef:refreshTeamTargetStr()
	if not self:isViewAlive() then return end

	local teamTarget = self._teamTarget
	local tltStr, nameStr
	tltStr = teamTarget:getTypeName()
	nameStr = teamTarget:getFullName()

	-- 如果是匹配，处理特例
	if self._isMatch and
		teamTarget:isQuickCrossMatch() and
		(not teamTarget:isElite()) and
		(not teamTarget:isChallenge()) then
		tltStr = L("CrossServerTips22")
	end

	-- 挑战赛，显示具体挑战赛的名字
	if teamTarget:isChallenge() then
		local targetId = app:sendMsg("PvpModel", "getChallengePlayId")
		local subTarget = self._model:getTeamTargetById(targetId)
		if subTarget then
			nameStr = tltStr .. "-" .. subTarget:getName()
		end
	end

	self._view:refreshTitle( tltStr )
	self._view:refreshTeamTargetStr( nameStr )
end

-- 上传投票确认状态
function ClassRef:_postConfirmVote()
	if self:isViewVisible() and 1 == self._idx and self._model:hasTeam() then
		self._model:reqConfirmVote()
	end
end

-- 帮助函数；开始PVP匹配
function ClassRef:_startPVPMatch(teamTarget)
	teamTarget = teamTarget or self._teamTarget
	local targetId = teamTarget.id
	app:sendMsg("LoadingModel", "setPlayId", targetId)
	self:_postConfirmVote()
	app:sendMsg( "PvpModel", "reqPvpMatch", targetId)
end

-- 跨服匹配副本
function ClassRef:_startCrossDungeonMatch(teamTarget)
	self:_postConfirmVote()
	teamTarget = teamTarget or self._teamTarget
	self._model:C2S_CrossDungeonMatch(teamTarget.id, function()
		-- 开始匹配，关闭准备界面
		self:closeView()
	end)
end

-- 匹配副本
function ClassRef:_startDungeonMatch(teamTarget)
	teamTarget = teamTarget or self._teamTarget
	local targetId = teamTarget.id

	-- 副本匹配暂时只支持五人地下城，其他的还是走_enterDungeons
	if teamTarget:isNormal() then
		self._model:C2S_StartTeamTargetMatch(targetId)
	else
		self:_enterDungeons(teamTarget)
	end
end

-- 帮助函数；进入副本
function ClassRef:_enterDungeons(teamTarget)
	local targetId = teamTarget and teamTarget.id or self._targetId
	app:sendMsg("LoadingModel", "setPlayId", targetId)

	teamTarget = teamTarget or self._teamTarget
	local dungeonId = teamTarget:getDungeonId()
	local dungeonSubId = teamTarget:getDungeonSubId()
	if dungeonId and dungeonSubId then
		-- 有dungeons指向性的玩法
		local dungeonsType = "normal"
		if teamTarget:isSpeed() then -- 竞速副本？
			dungeonsType = "race"
		elseif teamTarget:isSecret() then
			dungeonsType = "secret"
		end
		self:_postConfirmVote()
		DungeonManager:enterDungeonRequest(dungeonId, dungeonSubId, dungeonsType )
	else
		if Enums.TeamTarget.lionHeart == targetId then -- 狮心号角？
			self:_postConfirmVote()
			app:sendMsg( "NewActivityDungeonsModel", "reqEnterLionHorn" )
		elseif Enums.TeamTarget.fishVSZombie == targetId then -- 鱼人大战僵尸？
			self:_postConfirmVote()
			app.session:request("pb_zombie.C2S_EnterZombieBattle", {})
		elseif Enums.TeamTarget.worldBoss == targetId then -- 世界boss
			self:_postConfirmVote()
			app:sendMsg("BossModel", "reqWorldBossBattle")
		elseif Enums.TeamTarget.wildBoss == targetId then -- 野外boss
			self:_postConfirmVote()
			local itemData = teamTarget:getWildBossData()
			if itemData then
				app:sendMsg("BossModel", "reqSummonBoss", itemData[1], itemData[2])
			end
		elseif Enums.TeamTarget.dynastyBattle == targetId then -- 公会战
			self:_postConfirmVote()
			app:sendMsg("DynastyBattleModel", "reqEnterDynastyBattle")
		end
	end
	self:outDungeons()
end

function ClassRef:outDungeons()
	-- self:closeView()
	app:sendMsg("NewTeamMemberController", "closeView")
	app:sendMsg("TeamMatchController", "closeView")
	app:sendMsg("PvpController", "closeView")
	app:sendMsg("NewDungeonTypeController", "closeView")

	app:sendMsg("NewActivityDungeonsController", "closeView")
end

-- 取消投票
function ClassRef:_cancelVote()
	assert( self._model:isMyTeam(), " ------------->>>>>> 取消投票，身份居然不是队长？" )
	self._model:reqCancelVote()
end

function ClassRef:_onOperate( op, ... )
	-- dump({...}, "NewTeamReadyAndSettingController.onOperate data" .. op, 10)

	local data = ...

	if op == "TeamReadyAndSetting_applyJoinTeam" then -- 申请进入队伍
		self._model:reqApplyJoinTeam( self._otherTeam:getLeaderUid() )
	elseif op == "TeamReadyAndSetting_replayReady" then -- 准备确定
		self._model:reqReplyVote( data )
		if not data then
			self:closeView()
		end
	elseif op == "TeamReadyAndSetting_enterDungeons" then -- 进入副本
		local teamTarget = self._teamTarget
		local team = self._model:getTeam()
		local isAllReady = team:isAllReady()
		local isPve = teamTarget:isPveType()
		if isAllReady then
			if isPve then
				if self._isMatch then
					self:_startCrossDungeonMatch()
				else
					self:_enterDungeons()
				end
			else
				self:_startPVPMatch()
			end
		else
			if cc.isAlive(self._kickDlg) then
				self._kickDlg:removeFromParent()
				self._kickDlg = nil
			end
			if isPve then
				-- pve
				local dlg = display.newConfirmDialog( L("teamnotice3"),
					function() -- 确定
						if self._isMatch then
							self:_startCrossDungeonMatch()
						else
							self:_enterDungeons()
						end
					end)
				self._kickDlg = dlg
				UIHandler:addPopDialog( dlg )
			else
				-- pvp
				local dlg = display.newConfirmDialog( L("lua_code_text_53"),
					function() -- 确定
						-- 开始匹配
						self:_startPVPMatch()
					end)
				self._kickDlg = dlg
				UIHandler:addPopDialog( dlg )
			end
		end
	elseif op == "TeamReadyAndSetting_cancelVote" then -- 取消投票
		self:_cancelVote()
	elseif op == "TeamSetting_stopPlay" then
		--停止播放
		app:sendMsg("IMRecordController", "stopPlay")
	elseif op == "TeamSetting_playAudio" then
		--播放录音
		app:sendMsg("IMRecordController", "playAudio", data)
	elseif op == "TeamSetting_loadAudio" then
		--下载录音
		app:sendMsg("IMModel", "downloadAudio", ...)
	end
end

return ClassRef
